#导入相关库
import sys
import cv2
import numpy as np
from flask import Flask
from flask import render_template
from flask import request,jsonify
import os
from werkzeug.utils import secure_filename
sys.path.append("./recognition")
from recognition.my_facefeature import load_detector_recongizer
from recognition.my_facefeature import get_face_feature,cos_sim
from flask import Flask,render_template
from flask import redirect
from flask import url_for
from flask import request
from check.check_login import is_existed,exist_user,is_null
from check.check_regist import add_user
from reco_db import RecoDB
from reco_db2 import RecoDB2

app = Flask(__name__)
db = RecoDB()
db2 = RecoDB2()
register_feature = []
register_ID = []

print("从数据库读取特征和ID，图像路径")
rows = db.read_tb_featrue()
for row in rows:
    print("加载{} 特征：",format(row[0]))
    register_ID.append(row[0])
    feature = np.frombuffer(row[2],dtype=np.float32)
    register_feature.append(feature)

#加载人脸检测器，特征提取器
detector,recongizer = load_detector_recongizer(
    "./models/FaceDetector.onnx",
    "./models/face_recognizer_fast.onnx",)

#微信刷脸支付接口
@app.route('/hello', methods=['GET', 'POST'])
def hello_world():
    return render_template("zhifu4.html")

#收货信息接口
@app.route('/zhifu', methods=['GET', 'POST'])
def zhifu():
    return render_template("index2.html")

#支付成功后，返回到商店
@app.route('/zaigg', methods=['GET', 'POST'])
def zaigg():
    return render_template("index3.html")

#登录界面接口
@app.route('/', methods=['GET', 'POST'])
def welcom():
    return render_template("index1.html")

#添加面容界面接口
@app.route('/zhifu5', methods=['GET', 'POST'])
def zhifu5():
    return render_template("zhifu5.html")

#上传图片接口
@app.route('/upload', methods=['GET', 'POST'])
def upload_image():
    path2=""
    if request.method == "POST":
        f = request.files['the_file']
        face_id = request.form["face_id"]
        print("face_id:",face_id)
        basepath2 = os.path.dirname(__file__)  # 当前文件所在路径
        path2 = secure_filename(f.filename)
        upload_path2 = os.path.join(basepath2, './static/images/', secure_filename(f.filename))
        f.save(upload_path2)
        print(upload_path2)
        print("face_id:",face_id)
        #特征提取
        image = cv2.imread(upload_path2)
        feature = get_face_feature(detector,recongizer,image)
        register_feature.append(feature)
        register_ID.append(face_id)
        #存储到数据库中
        db.insert(face_id,upload_path2,feature) 
    return render_template("zhifu4.html",id="xxx",conf=0.0,path2=upload_path2)

#微信小程序上传图片-注册账号测试接口
@app.route('/upload21', methods=['GET', 'POST'])
def upload21():
    return render_template("testreco.html")

#微信小程序上传图片注册账号：手机号、名字、密码接口
@app.route('/upload2', methods=['GET', 'POST'])
def upload_image2():
    path22=""
    if request.method == "POST":
        f = request.files['the_file']
        face_id = request.form["face_id"]
        face_phone = request.form["face_phone"]
        face_password = request.form["face_password"]
        print("face_id:",face_id)
        basepath3 = os.path.dirname(__file__)  # 当前文件所在路径
        path22 = secure_filename(f.filename)
        upload_path3 = os.path.join(basepath3, './static/images/', secure_filename(f.filename))
        f.save(upload_path3)
        #特征提取
        image = cv2.imread(upload_path3)
        feature = get_face_feature(detector,recongizer,image)
        register_feature.append(feature)
        register_ID.append(face_id)
        #存储到数据库中
        db2.insert(face_phone,face_id,face_password,upload_path3,feature) 
    return render_template("hello.html")

#web：识别：上传图片接口，并识别
@app.route('/recogniz', methods=['GET', 'POST'])
def recogniz():
    path=""
    if request.method == "POST":
        f = request.files['the_file']

        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        path = secure_filename(f.filename)
        upload_path = os.path.join(basepath, './static/images/', secure_filename(f.filename))
        f.save(upload_path)
        print(upload_path)
        # f.save("./images/upload/b.jpg")
        #特征提取
        image = cv2.imread(upload_path)
        feature = get_face_feature(detector,recongizer,image)
        #特征比较
        sims = []
        for y in register_feature:
            sim = cos_sim(feature,y)
            sims.append(sim)#跟注册比较并存下相似度
        #3、取出相似度最低的，并且大于设定的阈值
        max_index = np.argmax(np.array(sims))#求数组最大的下标
        max_sim = sims[max_index]
        max_id = register_ID[max_index]
        if max_sim > 0.9:
            print("识别结果：{},相似度：{}".format(max_id,max_sim))
            ID = max_id
            conf = max_sim
            return render_template("fuqian.html")
        else:
            print("识别结果：unkonw")
            conf = max_sim
            return render_template("fuqianshibai.html",conf=conf)
        return render_template("testhrml.html",id=ID,conf=conf,path=upload_path)

@app.route("/upload_user_pwd",methods=['GET', 'POST'])
def upload_user_pwd():
    if request.method == "POST":
        user = request.form["user"]
        pwd = request.form["pwd"]
    data = {
        "dode":200,
        "msg":"登陆成功"
    }
    return jsonify(data)
#web端：账号注册接口
@app.route("/regiser",methods=["GET", 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if is_null(username,password):
            login_massage = "温馨提示：账号和密码是必填"
            return render_template('register.html', message=login_massage)
        elif exist_user(username):
            login_massage = "温馨提示：用户已存在，请直接登录"
            # return redirect(url_for('user_login'))
            return render_template('register.html', message=login_massage)
        else:
            add_user(request.form['username'], request.form['password'] )
            return render_template('index3.html', username=username)
    return render_template('register.html')
#web端：账号登录接口
@app.route('/user_login',methods=['GET','POST'])
def user_login():
    if request.method=='POST':  # 注册发送的请求为POST请求
        username = request.form['username']
        password = request.form['password']
        if is_null(username,password):
            login_massage = "温馨提示：账号和密码是必填"
            return render_template('index1.html', message=login_massage)
        elif is_existed(username, password):
            return render_template('index3.html', username=username)
        elif exist_user(username):
            login_massage = "温馨提示：密码错误，请输入正确密码"
            return render_template('index1.html', message=login_massage)
        else:
            login_massage = "温馨提示：不存在该用户，请先注册"
            return render_template('index1.html', message=login_massage)
    return render_template('index1.html')

if __name__ == '__main__':
    app.run(port=3000)#端口port的范围：0-65536